package com.example.factory.data.helper;

import android.text.TextUtils;
import android.util.Log;

import com.example.common.factory.data.DataSource;
import com.example.factory.Factory;
import com.example.factory.R;
import com.example.factory.model.api.RspModel;
import com.example.factory.model.api.account.AccountRspModel;
import com.example.factory.model.api.account.LoginModel;
import com.example.factory.model.api.account.RegisterModel;
import com.example.factory.model.db.AppDatabase;
import com.example.factory.model.db.User;
import com.example.factory.net.Network;
import com.example.factory.net.RemoteService;
import com.example.factory.persistence.Account;
import com.raizlabs.android.dbflow.config.DatabaseDefinition;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import com.raizlabs.android.dbflow.structure.database.transaction.ITransaction;
import com.raizlabs.android.dbflow.structure.database.transaction.TransactionWrapper;

import javax.security.auth.login.LoginException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author:0.2℃
 * @date： 2022-01-01 18:03
 * @version:
 * @Description ：
 */
public class AccountHelper {
    private static final String TAG = "AccountHelper";

    /**
     * 注册的接口，异步的调用
     * @param model     传递一个注册的model进来
     * @param callback  成功与失败的接口回送
     */
    public static void register(RegisterModel model,final DataSource.Callback<User> callback) {
        // 调用Retrofit对我们的网络请求接口做代理
        RemoteService service = Network.remote();
        // 得到一个Call
        Call<RspModel<AccountRspModel>> call = service.accountRegister(model);
        // 异步的请求
        call.enqueue(new AccountRspCallback(callback));
    }

    /**
     * 登录的接口调用，异步的调用
     * @param model LoginModel
     * @param callback DataSource.Callback<User>
     */
    public static void login(LoginModel model, final DataSource.Callback<User> callback) {
        // 调用Retrofit对我们的网络请求接口做代理
        RemoteService service = Network.remote();
        // 得到一个call
        Call<RspModel<AccountRspModel>> call = service.accountLogin(model);
        call.enqueue(new AccountRspCallback(callback));
    }

    /**
     * 对设备ID进行绑定的操作
     * @param callback
     */
    public static void bindPush(final DataSource.Callback<User> callback) {
        // 检查是否为空
        String pushId = Account.getPushId();
        if (TextUtils.isEmpty(pushId)) {
            return;
        }

        RemoteService service = Network.remote();
        Call<RspModel<AccountRspModel>> call = service.accountBind(pushId);
        call.enqueue(new AccountRspCallback(callback));

    }

    private static class AccountRspCallback implements Callback<RspModel<AccountRspModel>>{
        final DataSource.Callback<User> callback;
        AccountRspCallback(DataSource.Callback<User> callback){
            this.callback = callback;
        }
        @Override
        public void onResponse(Call<RspModel<AccountRspModel>> call, Response<RspModel<AccountRspModel>> response) {
            RspModel<AccountRspModel> rspModel = response.body();
            if (rspModel.success()) {
                AccountRspModel result = rspModel.getResult();

                User user = result.getUser();
                // 第一种，直接保存
                user.save();

                        /*
                        // 第二种，通过ModelAdapter的方式保存，这种方式和方式本质上是一样的
                        // 不过第二种是可以支持存储集合的
                        FlowManager.getModelAdapter(User.class)
                                .save(user);
                        // 第三种，使用事务存储
                        DatabaseDefinition definition = FlowManager.getDatabase(AppDatabase.class);
                        definition.beginTransactionAsync(new ITransaction() {
                            @Override
                            public void execute(DatabaseWrapper databaseWrapper) {
                                FlowManager.getModelAdapter(User.class)
                                        .save(user);
                            }
                        }).build().execute();
                        */
               Account.login(result);

               if (result.isBind()) {
                   // 设置绑定状态
                   Account.setBind(true);
                   // 如果已经绑定了，进行数据加载接口的回调
                   if (callback != null) {
                       callback.onDataLoaded(user);
                   }
               } else {
                   // 唤起绑定的接口
                   bindPush(callback);
               }
            } else {
                Log.e(TAG, "onResponse >>> " + response.toString());
                Factory.decodeRspCode(rspModel, callback);
            }
        }

        @Override
        public void onFailure(Call<RspModel<AccountRspModel>> call, Throwable t) {
            Log.e(TAG, "onFailure >>> 请求失败" );
            if (callback != null) {
                callback.onDataNotAvailable(R.string.data_network_error);
            }
        }
    }
}
